package com.example.queue09.queue;

/**
 * 动态数组，尾下标指向数组尾时，没放满就左移所有元素
 * @auther lijiewei
 * @date 2021/8/23 14:11
 */
public class DynamicArrayQueue {

    //数组
    private String[] items;
    //队列容量
    private int size = 0;
    //头下标
    private int head = 0;
    //尾下标
    private int tail = 0;

    public DynamicArrayQueue(int capacity) {
        if (capacity <= 0) {
            throw new RuntimeException("容量必须大于0");
        }
        items = new String[capacity];
        size = capacity;
    }

    /**
     * 入队
     * @param item 数据
     * @return
     * @author lijiewei
     * @date   2021/8/23 14:16
     */
    public boolean enqueue(String item) {
        if (tail == size) {
            //满队
            if (head==0) {
                return false;
            }
            //左移元素
            for (int i = head; i < tail; i++) {
                items[i-head] = items[i];
            }
            tail -= head;
            head = 0;
        }
        items[tail] = item;
        tail++;
        return true;
    }

    /**
     * 出队
     * @return
     * @author lijiewei
     * @date   2021/8/23 14:25
     */
    public String dequeue() {
        //空队
        if(head == tail) {
            return null;
        }
        String res = items[head];
        head++;
        return res;
    }

    /**
     * 打印所有元素
     * @return
     * @author lijiewei
     * @date   2021/8/23 13:59
     */
    public void printAll() {
        for (int i = head; i < tail; i++) {
            System.out.print(items[i] + " ");
        }
        System.out.println();
    }
}
